package com.tramp.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tramp.basic.entity.Role;
import com.tramp.basic.service.RoleService;
import com.tramp.basic.vo.RoleVO;
import com.tramp.frame.server.base.BaseController;
import com.tramp.frame.server.base.ResultData;
import com.tramp.frame.server.exception.GenericException;

/**
 * Created by chen on 2017/11/9.
 */
@Controller
@RequestMapping("/role/")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;

	/**
	 * 列表页
	 *
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list() {

		return "role/list";
	}

	/**
	 * 权限编辑页
	 *
	 * @return
	 */
	@RequestMapping(value = "menuAuth")
	public String menuAuth() {

		return "role/menuAuth";
	}


	/**
	 * 保存权限
	 * @return
	 */
	@RequestMapping("/menuAuthSave")
	@ResponseBody
	public ResultData menuAuthSave(@RequestBody RoleVO roleVO) {
		roleService.menuAuthSave(roleVO);
		return success(roleVO);
	}

	/**
	 * 添加页
	 *
	 * @return
	 */
	@RequestMapping(value = "add")
	public String add() {

		return "role/add";
	}

	/**
	 * 列表数据
	 *
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public ResultData query(String name) {
		this.setPageSqlId("RoleBaseDao.listByEntity");
		Role role = new Role();
		role.setName(name);
		List<Role> roleList = roleService.listByEntity(role);
		return successPage(roleList);
	}

	/**
	 * 保存
	 *
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public ResultData save(@RequestBody Role role) {
		if (StringUtils.isNotBlank(role.getId())) {
			roleService.update(role);
		}
		else {
			if (StringUtils.isBlank(role.getParentId())) {
				role.setParentId("0");
			}
			role.setCreateTime(new Date());
			roleService.insert(role);
		}
		return success(role);
	}

	/**
	 * 删除
	 *
	 * @return
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public ResultData remove(String id) {
		if (StringUtils.isBlank(id)) {
			throw new GenericException("参数错误");
		}
		roleService.deleteRole(id);
		return success(null);
	}

	/**
	 * 根据id查询详情
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("info")
	@ResponseBody
	public ResultData info(String id) {
		if (StringUtils.isBlank(id)) {
			throw new GenericException("参数错误");
		}
		RoleVO roleVO = roleService.getInfo(id);
		return success(roleVO);
	}

	/**
	 * 列表数据
	 * @return
	 */
	@RequestMapping("/select")
	@ResponseBody
	public ResultData select() {
		List<Role> roleList = roleService.listByEntity(new Role());
		return success(roleList);
	}
}
